'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
    throw err;
});

// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
// 给文本终端里面的字体上色
const chalk = require('react-dev-utils/chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
// 清除控制台
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
// node_modules\react-dev-utils\WebpackDevServerUtils.js
const {
    choosePort,
    createCompiler,
    prepareProxy,
    prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
// 开发模式打包完成后，自动打开浏览器
const openBrowser = require('react-dev-utils/openBrowser');
const semver = require('semver');
const paths = require('../config/paths');

const configFactory = require('../webpack.config');
const createDevServerConfig = require('../webpack.devServer');

const getClientEnvironment = require('../config/env');
const react = require(require.resolve('react', { paths: [paths.appPath] }));

const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
const useYarn = fs.existsSync(paths.yarnLockFile);
// 检测到其运行时绑定了文本终端
const isInteractive = process.stdout.isTTY;

// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
    process.exit(1);
}

// Tools like Cloud9 rely on this.
const port = 9000;
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || port;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
    console.log(
        chalk.cyan(
            `Attempting to bind to HOST environment variable: ${chalk.yellow(
                chalk.bold(process.env.HOST)
            )}`
        )
    );
    console.log(
        `If this was unintentional, check that you haven't mistakenly set it in your shell.`
    );
    console.log(
        `Learn more here: ${chalk.yellow('https://cra.link/advanced-config')}`
    );
    console.log();
}

// 检查当前项目有没有设置browserlist -- 项目适配的浏览器种类及版本
// 第一个参数，传入项目路径，让browserslist这个包去查找配置
// 第二个参数是检测当前运行时有无绑定文本终端，这个是在检测不到browserlist配置的时候用于提示
// 如果有配置则直接resolve
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive).then(() => {
    // 自动检测默认端口号有无占用，有则令设一个port
    // 这里需要用户去确认是否使用默认，有个异步操作，
    // 所以这个函数也返回一个promise
    return choosePort(HOST, DEFAULT_PORT);
}).then(port => {
    if (port == null) {
        // 没有找到端口号
        return;
    }
    // 通过执行webpack.config.js的导出函数的执行，获取webpack除devServer外的配置
    const config = configFactory('development');
    // 检查当前环境下的http协议类型
    const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
    // 获取app名称
    const appName = require(paths.appPackageJson).name;
    // 检查当前项目是否使用typescript
    const useTypeScript = fs.existsSync(paths.appTsConfig);
    const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
    // 基于协议、Host为终端、浏览器生成url
    const urls = prepareUrls(
        protocol,
        HOST,
        port,
        paths.publicUrlOrPath.slice(0, -1)
    );
    const devSocket = {
        warnings: warnings =>
            devServer.sockWrite(devServer.sockets, 'warnings', warnings),
        errors: errors =>
            devServer.sockWrite(devServer.sockets, 'errors', errors),
    };
    // Create a webpack compiler that is configured with custom messages.
    // 核心就是通过调用webpack生成编译器 const compiler = webpack(config)
    // 在这基础之上，自定义compiler不同生命周期的行为（Hook）
    const compiler = createCompiler({
        appName,
        config,
        devSocket,
        urls,
        useYarn,
        useTypeScript,
        tscCompileOnError,
        webpack,
    });
    // 加载代理设置
    // 直接从package.json这个文件中找
    const proxySetting = require(paths.appPackageJson).proxy;
    // 基于代理设置生成
    const proxyConfig = prepareProxy(
        proxySetting,
        paths.appPublic,
        paths.publicUrlOrPath
    );
    // Serve webpack assets generated by the compiler over a web server.
    const serverConfig = createDevServerConfig(
        proxyConfig,
        urls.lanUrlForConfig
    );
    const devServer = new WebpackDevServer(compiler, serverConfig);
    // Launch WebpackDevServer.
    devServer.listen(port, HOST, err => {
        if (err) {
            return console.log(err);
        }
        if (isInteractive) {
            clearConsole();
        }

        if (env.raw.FAST_REFRESH && semver.lt(react.version, '16.10.0')) {
            console.log(
                chalk.yellow(
                    `Fast Refresh requires React 16.10 or higher. You are using React ${react.version}.`
                )
            );
        }

        console.log(chalk.cyan('Starting the development server...\n'));
        openBrowser(urls.localUrlForBrowser);
    });

    ['SIGINT', 'SIGTERM'].forEach(function (sig) {
        process.on(sig, function () {
            devServer.close();
            process.exit();
        });
    });

    if (process.env.CI !== 'true') {
        // Gracefully exit when stdin ends
        process.stdin.on('end', function () {
            devServer.close();
            process.exit();
        });
    }
}).catch(err => {
    if (err && err.message) {
        console.log(err.message);
    }
    // 退出进程，参数代码代表不同状态
    process.exit(1);
});